package com.reviewit.mbean;

import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import com.reviewit.dao.DocTypeDao;
import com.reviewit.model.DocType;

@ManagedBean
@SessionScoped
public class DocTypeBean extends GenericBean implements Serializable,
		NavigationRules {
	private static final long serialVersionUID = 1L;

	private DataModel<DocType> docTypes;
	private DocType docType;
	private DocTypeDao dao;

	public DocTypeBean() {
		super();
		this.log = Logger.getLogger(this.getClass().getName());
		this.dao = DocTypeDao.getInstance();
		this.docType = new DocType();
	}

	public DocType getDocType() {
		return docType;
	}

	public void setDocType(DocType docType) {
		this.docType = docType;
	}

	public void setDocTypes(DataModel<DocType> docTypes) {
		this.docTypes = docTypes;
	}

	public DataModel<DocType> getDocTypes() {
		List<DocType> list = dao.find().asList();
		docTypes = new ListDataModel<DocType>(list);
		return docTypes;
	}

	public void select() {
		setDocType(docTypes.getRowData());
	}

	public String findById() {
		DocType obj = dao.findOne("id", docType.getId());
		setDocType(obj);

		return NavigationRules.FIND_ENTITY;
	}

	public String saveOrUpdate() {
		DocType obj = dao.findOne("id", docType.getId());
		if (obj == null) {
			return this.update();
		} else {
			return this.save();
		}
	}

	public String save() {
		try {
			dao.save(docType);
		} catch (Exception e) {
			return e.getMessage();
		}

		setDocType(new DocType());
		return "DocType saved!";
	}

	public String update() {
		try {
			dao.save(docType);
		} catch (Exception e) {
			return e.getMessage();
		}

		setDocType(new DocType());
		return "DocType updated!";
	}

	public String delete() {
		try {
			dao.delete(docType);
		} catch (Exception e) {
			return e.getMessage();
		}

		setDocType(new DocType());
		return "DocType deleted!";
	}

	public String back() {
		return NavigationRules.BACK_CADASTRO;
	}

	public void nnew() {
		setDocType(new DocType());
	}
}